package cn.akwangl.tools.atomic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 演示多线程下Atomic原子类与非原子类线程安全问题.
 *
 * @author 阿坤同学
 * @date 2022-11-16 9:58
 */
public class AtomicIntegerDemo {

    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    private static volatile int count = 0;


    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        CountTask countTask = new CountTask();

        for (int i = 0; i < 200; i++) {
            executorService.submit(countTask);
        }

        executorService.shutdown();
        while (!executorService.isTerminated()) {

        }

        System.out.println("原子类统计数: " + atomicInteger.get());
        System.out.println("非原子类统计数: " + count);
    }


    static class CountTask implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 20000; i++) {
                atomicInteger.getAndIncrement();
                count++;
            }
        }
    }
}
